// 206. 反转链表

// 反转一个单链表。

// 示例:
// 输入: 1->2->3->4->5->NULL
// 输出: 5->4->3->2->1->NULL

// 进阶:
// 你可以迭代或递归地反转链表。你能否用两种方法解决这道题？

const { ListNode } = require("./common.js");

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
  let result;
  let current = head;
  while (current) {
    const next = current.next;
    current.next = result;
    result = current;
    current = next;
  }
  return result;
};

var reverseList2 = function (head) {
  if (!head || !head.next) {
    return head;
  }
  const result = reverseList2(head.next);
  head.next.next = head;
  head.next = null;
  return result;
};

console.log(
  reverseList(
    new ListNode(
      1,
      new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null))))
    )
  ).toString()
);
console.log(
  reverseList2(
    new ListNode(
      1,
      new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null))))
    )
  ).toString()
);

module.exports.reverseList = reverseList;
